package com.younio.local.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.younio.local.driver.DerbyDriver;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;

/*/**
 * @desc #      url: jdbc:derby:D:/meterdb;user=tnma;password=tianma;
#      driverClassName: org.apache.derby.jdbc.EmbeddedDriver
#      driver-class-name: org.apache.derby.jdbc.EmbeddedDriver
 * @author lan [1728209643@qq.com]
 * @create 2019/1/2 9:17
 * @param 
 * @return 
 */
@Configuration
public class DynamicDataSourceConfig {

    @Setter
    @Value("${spring.datasource.derby.url}")
    private String derbyUrl;


    @Bean(name = "derby")
    public DataSource dataSource1() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.younio.local.driver.DerbyDriver");
        dataSource.setUrl(derbyUrl);
        dataSource.setDriver(new DerbyDriver());
        dataSource.setMaxActive(30);
        dataSource.setTestWhileIdle(false);
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxOpenPreparedStatements(20);
        return dataSource;
    }

    @Bean(name = "mysql")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource dataSource2() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setMaxActive(20);
        dataSource.setInitialSize(10);
        dataSource.setTestWhileIdle(true);
        return dataSource;
    }

    @Bean
    @Primary
    public AbstractRoutingDataSource abstractRoutingDataSource() {
        DynamicDataSource dataSources = new DynamicDataSource();
        dataSources.setTargetDataSources(new HashMap<>());
        return dataSources;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("abstractRoutingDataSource") DynamicDataSource dynamicDataSource) {
        return new DataSourceTransactionManager(dynamicDataSource);
    }
}
